package cn.fl.framework.base.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.constant.GaodeConstant;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Gaode 高德地图工具类
 * GaodeUtils
 */
public class GaodeUtils {
	
	//返回起始地startAddr与目的地endAddr之间的距离，单位：米 
	public static Long getDistance(final String startLonLat, final String endLonLat){  
		Long result = new Long(0);
        if(StringUtils.isNotEmpty(startLonLat) && StringUtils.isNotEmpty(endLonLat)){
            String queryUrl = GaodeConstant.DISTANCE_API_URL+"key="+GaodeConstant.STATIC_KEY+"&origins="+startLonLat+"&destination="+endLonLat;  
            String queryResult = getResponse(queryUrl);
            
            JSONObject json = JSONObject.fromObject(queryResult);  
            JSONArray jsonArray = json.getJSONArray("results");  
      
            result = Long.parseLong(JSONObject.fromObject(jsonArray.getString(0)).get("distance").toString());  
        }
        return result; 
    }
	
	//返回输入地址address的经纬度信息, 格式是 经度,纬度 
	public static String getLonLat(String address){
		String result = null;
		if(StringUtils.isNotEmpty(address)){
	        String queryUrl = GaodeConstant.GEOCODE_GEO_API_URL+"key="+GaodeConstant.STATIC_KEY+"&address="+address;  
	        String queryResult = getResponse(queryUrl);  //高德接口返回的是JSON格式的字符串  
	  
	        JSONObject json = JSONObject.fromObject(queryResult);  
	        JSONArray jsonArray = json.getJSONArray("geocodes");
	        result = JSONObject.fromObject(jsonArray.getString(0)).get("location").toString();
		}
        return result;
    } 
	
	//用JAVA发起http请求，并返回json格式的结果  
	private static String getResponse(String serverUrl){  
    	String result = null;
        try {  
            URL url = new URL(serverUrl);  
            URLConnection conn = url.openConnection();  
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  
            result = in.readLine();  
            in.close();  
  
        } catch (MalformedURLException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return result;  
    }  
}
